/**
 * Octopus, an XMMS2 client.
 * Copyright (C) 2014 Octopus Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

namespace Octopus {
	public class Playlist : MedialibTracklist, IMedialibInfo, IComparable, ICollection {
		public signal void rename_finished (string name);
		private string _new_name;

		public Playlist (string name, bool stored_in_medialib) {
			Object (name: name, stored_in_medialib: stored_in_medialib);
		}

		public void request_data () {
			add (this);
			add_finished ();
		}

		public string get_compare_string () {
			return name;
		}

		public string get_namespace () {
			return Xmms.COLLECTION_NS_PLAYLISTS;
		}

		public void xmms_collection_remove () { 
			Global.get ().get_xmms_client ().get_xmms ().coll_remove (name, Xmms.COLLECTION_NS_PLAYLISTS);
		}

		public void xmms_playlist_load () {
			Global.get ().get_xmms_client ().get_xmms ().playlist_load (name);
		}

		public void xmms_collection_rename (string new_name) {
			_new_name =  new_name;
			Global.get ().get_xmms_client ().get_xmms ().coll_rename (name, new_name, Xmms.COLLECTION_NS_PLAYLISTS).notifier_set ((val) => {
				if (val.is_error ()) {
					unowned string error;
					if (val.get_error(out error)) {
						Global.get ().message ("error: %s".printf (error));
						GLib.warning ("error renaming collection: %s", error);
					}
					rename_finished (name);
				}
				name = _new_name;
				rename_finished (_new_name);
				return true;
			});
		}

		public void xmms_collection_create (string new_name) {
			if (new_name == Global.get ().get_active_playlist ().name) {
				Global.get ().message ("error: can't overwrite active playlist");
				GLib.warning ("error: can't overwrite active playlist");
				return;
			}
			_new_name =  new_name;
			Global.get ().get_xmms_client ().get_xmms ().playlist_create (new_name).notifier_set ((val) => {
				if (val.is_error ()) {
					unowned string error;
					if (val.get_error(out error)) {
						Global.get ().message ("error: %s".printf (error));
						GLib.warning ("error creating collection: %s", error);
					}
				}
				name = _new_name;
				stored_in_medialib = true;
				return true;
			});
		}
	}
}
